//
//  EditViewController.m
//  Findif
//
//  Created by appdev on 2018/10/29.
//  Copyright © 2018 Cicel Chen. All rights reserved.
//

#import "EditViewController.h"
#import "AlbumTableViewCell.h"
#import "IconTableViewCell.h"
#import "UserInfoTableViewCell.h"
#import "MyAlbumViewController.h"
#import <AFHTTPSessionManager.h>

@interface EditViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UserInfoTableViewCellDelegate,UIPickerViewDelegate,UIPickerViewDataSource>{
    
    UIImagePickerController *_imagePickerController;
    NSInteger _ageIndex;
}

@property (nonatomic,weak)UITableView * tableView;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, strong)UIAlertController * genderAlertVC;
@property (nonatomic, strong)NSIndexPath * iconIndexPath;
@property (nonatomic, strong)UserInfoTableViewCell * userInfoCell;
@property (nonatomic, strong)IconTableViewCell * iconCell;
@property (nonatomic, copy)NSString * state;

@property (nonatomic, copy)NSString * age;
@property (nonatomic, copy)NSString * ageid;
@property (nonatomic, strong)NSArray * dataArray;
@property (nonatomic, strong)UIView * bgView;
@property (nonatomic, strong)UIPickerView * pickerView;

@property (nonatomic, strong)NSArray * albumArray;
@property (nonatomic, copy)NSString * album;
@property (nonatomic, copy)NSString * noData;

@end

@implementation EditViewController


- (void)viewWillAppear:(BOOL)animated{
    
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    _ageIndex = 0;
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
    [self setupGenderAlertVC];
    [self setupPivkerView];
}


- (void)loadData{
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    [[ZRNetworkTool sharedTool] getAgeListResultWithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            self.dataArray = responseData[@"data"];
            
            [self.pickerView reloadAllComponents];
        }
    }];
    
    self.albumArray = nil;
    [[ZRNetworkTool sharedTool] getUserPhotoAlbumWithUser_id:user_id ResultWithBlock:^(BOOL success, id responseData) {
        
        NSLog(@"res===%@",responseData);
        if (success) {
            
            self.albumArray = responseData[@"data"];
            [self.tableView reloadData];
        }
        
//        if ([responseData[@"message"] isEqualToString:@"暂时没有相册"]) {
//
//            self.noData = @"noData";
//        }
    }];
    
}

- (void)setAlbumArray:(NSArray *)albumArray{

    _albumArray = albumArray;

    [self.tableView reloadData];
}

- (void)setupNav{
    
    self.title = @"编辑资料";

//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back(1)"] style:UIBarButtonItemStylePlain target:nil action:nil];
//    
//    self.navigationItem.backBarButtonItem = backItem;
}


- (void)setupUI{
    
    self.view.backgroundColor = ColorWithRGB(0xF4F5F6);
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF4F5F6);
//    tableView.rowHeight = 120 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.tableView = tableView;
    
    [self.tableView registerClass:[AlbumTableViewCell class] forCellReuseIdentifier:@"AlbumTableViewCell"];
    [self.tableView registerClass:[IconTableViewCell class] forCellReuseIdentifier:@"IconTableViewCell"];
    [self.tableView registerClass:[UserInfoTableViewCell class] forCellReuseIdentifier:@"UserInfoTableViewCell"];
    
    [self.view addSubview:self.tableView];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        AlbumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AlbumTableViewCell" forIndexPath:indexPath];
        
        //    cell.model = self.readListArray[indexPath.row];
//        if (self.noData) {
//            
//        }else{
            cell.array = self.albumArray;
//        }
    
        return cell;
    }else if (indexPath.section == 1) {
        
        self.iconCell = [tableView dequeueReusableCellWithIdentifier:@"IconTableViewCell" forIndexPath:indexPath];
//        cell.iconImageView.image =
        if (!self.state) {
            
            if ([self.dict[@"head_img"] isEqual:[NSNull null]]) {
                
                self.iconCell.iconImageView.image = [UIImage imageNamed:@"组12"];
            }else{
                
                
                NSString * usrlStr = [NSString stringWithFormat:@"%@%@",BASEURLSTR,self.dict[@"head_img"]];
                NSURL * url = [NSURL URLWithString:usrlStr];
                [self.iconCell.iconImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"组12"]];
            }
        }
        
        //    cell.model = self.readListArray[indexPath.row];
        
        return self.iconCell;
    }else{
        
        self.userInfoCell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoTableViewCell" forIndexPath:indexPath];
        
        self.userInfoCell.userInfoTableViewCellDelegate = self;
        //    cell.model = self.readListArray[indexPath.row];
        if ([self.dict[@"user_name"] isEqual:[NSNull null]]) {
            
            self.userInfoCell.nameTextFiled.placeholder = @"请输入您修改的昵称";
        }else{
            
            self.userInfoCell.nameTextFiled.text = self.dict[@"user_name"];
        }
        
        NSString * gender = [NSString stringWithFormat:@"%@",self.dict[@"sex"]];
        if ([gender isEqualToString:@"1"]) {
            
            [self.userInfoCell.genderButton setTitle:@"男" forState:UIControlStateNormal];
            self.userInfoCell.genderButton.selected = YES;
        }else if ([gender isEqualToString:@"2"]){
            
            [self.userInfoCell.genderButton setTitle:@"女" forState:UIControlStateNormal];
            self.userInfoCell.genderButton.selected = YES;
        }else{
            
             [self.userInfoCell.genderButton setTitle:@"请选择性别" forState:UIControlStateNormal];
            self.userInfoCell.genderButton.selected = NO;
        }
        
        if ([self.dict[@"personality_sign"] isEqual:[NSNull null]]) {
            
            self.userInfoCell.exploreFiled.text = @"请输入你的个性签名....";
            self.userInfoCell.exploreFiled.textColor = [UIColor lightGrayColor];
        }else{
            
            self.userInfoCell.exploreFiled.text = self.dict[@"personality_sign"];
            self.userInfoCell.exploreFiled.textColor = ZRBlackColor;
        }
        
        if ([self.dict[@"age"] isEqual:[NSNull null]]) {
            
            [self.userInfoCell.brithdayButton setTitle:@"请选择" forState:UIControlStateNormal];
            self.userInfoCell.brithdayButton.selected = NO;
        }else{
            
            [self.userInfoCell.brithdayButton setTitle:self.dict[@"age"] forState:UIControlStateNormal];
            self.userInfoCell.brithdayButton.selected = YES;
        }
        
        return self.userInfoCell;
    }
  
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 2) {
        
        return 203 * SCREENH6;
    }else if(indexPath.section == 1){
        
       return 70 * SCREENH6;
    }else{
        
       return 70 * SCREENH6;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 20 * SCREENH6;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        
        self.iconIndexPath = indexPath;

        
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {

            self.alertVC.popoverPresentationController.sourceView = self.view;
            self.alertVC.popoverPresentationController.sourceRect = CGRectMake(10 * SCREENH6,kScreenH - 150 * SCREENH6,355 * SCREENH6,150 * SCREENH6);
//            self.alertVC.modalPresentationStyle = UIModalPresentationFormSheet;
        }
        [self presentViewController:self.alertVC animated:YES completion:nil];
        
    }else if (indexPath.section == 0){
        
        HiddenBar;
        
        MyAlbumViewController * myAlbumVC = [MyAlbumViewController new];
        
        myAlbumVC.type = @"1";
        
        [self.navigationController pushViewController:myAlbumVC animated:YES];
    }
//    else if (indexPath.section == 2){
//
//        self.userInfoIndexPath = indexPath;
//
//        [self presentViewController:self.genderAlertVC animated:YES completion:nil];
//    }
}

- (void)setupPivkerView{
    
    self.bgView = [[UIView alloc]init];
    self.bgView.frame = CGRectMake(0, kScreenH, kScreenW, kScreenH / 3);
    self.bgView.backgroundColor = ZRWhiteColor;
    [self.view addSubview:self.bgView];
    
    UIView *btnView = [[UIView alloc]init];
    btnView.frame = CGRectMake(0, 0, kScreenW, 40 * SCREENH6);
    btnView.backgroundColor = ColorWithRGB(0xababab);
    [self.bgView addSubview:btnView];
    
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame = CGRectMake(10 * SCREENH6, 5 * SCREENH6, 60 * SCREENH6, 30 * SCREENH6);
    [sureBtn setTitle:@"取消" forState:UIControlStateNormal];
    [sureBtn setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(cancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [btnView addSubview:sureBtn];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(self.view.frame.size.width - 70 * SCREENH6, 5 * SCREENH6, 60 * SCREENH6, 30 * SCREENH6);
    [cancelBtn setTitle:@"确定" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(sureBtn) forControlEvents:UIControlEventTouchUpInside];
    [btnView addSubview:cancelBtn];
    
    float height = kScreenH / 3 - 40 * SCREENH6;
    self.pickerView = [[UIPickerView alloc]init];
    self.pickerView.frame = CGRectMake(0, 40 * SCREENH6, kScreenW, height);
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.bgView addSubview:self.pickerView];
}


// 列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// 每列有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    return self.dataArray.count;
}


// 返回每一行的内容
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    NSDictionary * dict = self.dataArray[row];
    
    
    
    NSString * bankInfo = [NSString stringWithFormat:@"%@",dict[@"age"]];

    return bankInfo;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    _ageIndex = row;
}


- (void)cancelBtn{
    
    
    [UIView animateWithDuration:0.5 animations:^{
        self.bgView.frame = CGRectMake(0, self.view.frame.size.height, kScreenW, kScreenH / 3);
    } completion:^(BOOL finished) {
    }];
    
}


- (void)sureBtn{
    
    NSDictionary * dict = self.dataArray[_ageIndex];
    
    NSString * age = dict[@"age"];
    NSString * ID = dict[@"id"];
    
    [self.userInfoCell.brithdayButton setTitle:age forState:UIControlStateNormal];
    self.userInfoCell.brithdayButton.selected = YES;
    
    [[ZRNetworkTool sharedTool] updateUserInfoWithUpdate_Class:@"age" WithUpdate_content:ID WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
        }
    }];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.bgView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, kScreenH / 3);
    } completion:^(BOOL finished) {
    }];
}




- (void)clickItemButton:(NSString *)type{
    
    if ([type isEqualToString:@"gender"]) {
        
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
            
            self.genderAlertVC.popoverPresentationController.sourceView = self.view;
            self.genderAlertVC.popoverPresentationController.sourceRect = CGRectMake(10 * SCREENH6,kScreenH - 150 * SCREENH6,355 * SCREENH6,150 * SCREENH6);
            //            self.alertVC.modalPresentationStyle = UIModalPresentationFormSheet;
        }
        [self presentViewController:self.genderAlertVC animated:YES completion:nil];
    }else{
        
//        [self presentDateController];
        [UIView animateWithDuration:0.5 animations:^{
            self.bgView.frame = CGRectMake(0, kScreenH - kScreenH / 3, kScreenW, kScreenH / 3);
        }];
    }
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}


- (void)setupGenderAlertVC{
    
    self.genderAlertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择性别" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self.userInfoCell.genderButton setTitle:@"男" forState:UIControlStateNormal];
        self.userInfoCell.genderButton.selected = YES;
        
        [[ZRNetworkTool sharedTool] updateUserInfoWithUpdate_Class:@"sex" WithUpdate_content:@"1" WithBlock:^(BOOL success, id responseData) {
            
            if (success) {
                
            }
        }];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self.userInfoCell.genderButton setTitle:@"女" forState:UIControlStateNormal];
        self.userInfoCell.genderButton.selected = YES;
        
        [[ZRNetworkTool sharedTool] updateUserInfoWithUpdate_Class:@"sex" WithUpdate_content:@"2" WithBlock:^(BOOL success, id responseData) {
            
            if (success) {
                
            }
        }];
    }];
    
    [self.genderAlertVC addAction:camerAction];
    [self.genderAlertVC addAction:albumsAction];
}

#pragma mark -实现图片选择器代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);
    NSString *base64Data = [frontImageData base64EncodedStringWithOptions:0];
    NSString * reslut = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",base64Data];
    
    NSDictionary * dic = @{@"headImg":reslut,@"user_id":user_id};


    [[NetworkTool sharedTools] POST:@"Api/updateUserHeadImg" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        int code = [responseObject[@"code"] intValue];
        
        if (code == 200) {
            
            self.iconCell.image = image;
            self.state = @"have";
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];

        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error---%@",error);
    }];
    
}

//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}



@end
